<?php
/*pc端客服*/
namespace app\mobile\controller;

use app\api\model\ChatMsg;
use app\api\model\Client;
use app\api\model\KfReply;
use app\api\model\Users;
use plugin\filter;
use plugin\Gateway;
use think\Session;

class Index extends Common
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        //登录检测
        if(!$this->check_login())
        {
            $this->login();
        }
        //关闭同个浏览器多个对话页面的客户端链接
        $this->closeSameClient();
        $client_List = [];
        if($this->CurrentUserIsKf())
        {
            $chatMsg = new ChatMsg();
            $client = new Client($this->modelDefaultParam());
            //获取与客服聊天最近的用户
            $data = $chatMsg->getLogUser($this->getCurrentUserid(true));
            //获取所有在线的客户端id
            $allKfClientId = $client->getAllOnLineClientId();
            //如果没有聊天记录，则获取当前所有用户
            if(!empty($data))
            {
                $client_List = $client->setOnLineState($data,$allKfClientId);
            }
            else
            {
                $userModel = new Users($this->modelDefaultParam());
                //获取所有用户
                $client_List = $userModel->getAllOnLineUser($allKfClientId);
            }
        }
        else
        {
            $client_List = $this->GetKfList();
        }


        $photo_path = $this->config('domain')."/";
        $this->assign([
            'client_list' => $client_List,
            'userPhotoOnLine' =>$photo_path .$this->config('userPhotoOnLine'),
            'userPhotoOffLine'=>$photo_path.$this->config('userPhotoOffLine'),
            'kfPhotoOnLine' =>$photo_path.$this->config('kfPhotoOnLine'),
            'kfPhotoOffLine'=>$photo_path.$this->config('kfPhotoOffLine'),
            'domain_ip'  => $this->config('domain_ip'),
            'is_kf'         => $this->CurrentUserIsKf() ? 1 : 0
        ]);

        return $this->fetch();
    }

    //客服不在线时，进行发送该信息
    public function sendKfOffLineText($client_id)
    {
        $KfReplyModel = new KfReply();
        $reply = json_encode($KfReplyModel->total(['pageLimit'=>7]),JSON_UNESCAPED_UNICODE);
        if(empty($reply)) return;
        //发送7条记录
        $input = [
            'to_client_id' => $client_id,
            'type'  => 'OffLineText',
            'msg'   => $reply
        ];
        $userModel  = new Client($this->modelDefaultParam());
        $userModel->send_text($input);
    }

    //获取客服列表
    private function GetKfList()
    {
        //当前登陆者是用户，则获取客服列表
        $client = new Client($this->modelDefaultParam());
        $KfModel = new \app\api\model\Kf($this->modelDefaultParam());
        //获取所有在线的客户端id
        $allKfClientId = $client->getAllOnLineClientId();
        //获取所有客服列表
        $list = $KfModel->getAllKf($allKfClientId);
        return $list;
    }

    //获取用户列表
    private function GetUserList()
    {
        $client = new Client($this->modelDefaultParam());
        $userModel = new Users($this->modelDefaultParam());
        //获取所有在线的客户端id
        $allKfClientId = $client->getAllOnLineClientId();
        //获取所有用户
        $list = $userModel->getAllOnLineUser($allKfClientId);
        return $list;
    }

    //聊天页面
    public function chat()
    {
        //获取聊天对象客户端id
        $pid                = input('get.pid');
        //检查聊天对象正确性
        if(!$this->chkCurrentTarget($pid)) exit("参数错误");

        //获取聊天对象的客户端信息
        $users = $this->getUserMsg($pid);
        if(empty($users)) exit('聊天对象不存在');
        //如果当前用户不是客服 并且聊天对象不是客服
        if($users['is_kf'] != 1 && !$this->isKf($this->getCurrentUserid(true))) $this->error('请选择客服人员进行对话哦');
        $photo_path = $this->config('domain')."/";
        //模板渲染
        $this->assign([
            'client_user'=> $users,
            'userPhotoOnLine' =>$photo_path .$this->config('userPhotoOnLine'),
            'userPhotoOffLine'=>$photo_path.$this->config('userPhotoOffLine'),
            'kfPhotoOnLine' =>$photo_path.$this->config('kfPhotoOnLine'),
            'kfPhotoOffLine'=>$photo_path.$this->config('kfPhotoOffLine'),
            'token'      => $this->getCurrentToken(),
            'domain_ip'  => $this->config('domain_ip'),
            'is_kf'         => $this->CurrentUserIsKf() ? 1 : 0
        ]);


        return $this->fetch('chat');
    }


    //获取一个用户信息以及初始化在线离线
    protected function getUserMsg($client_id)
    {
        //获取客户端基本消息
        $userModel  = new Users($this->modelDefaultParam());
        $users      = $userModel->user_info(['enc_client_id'=>$client_id]);
        if(empty($users)) return null;
        //获取未查看历史记录
        $chatMsg = new ChatMsg();
        $users['no_skim'] = $chatMsg->getOneNoSkimLog($client_id,$this->getCurrentUserid(true));
        //user_id加密
        $users['client_id'] = $this->EncUserid($users['client_id']);
        //判断是否在线
        $users['lineState'] = $this->clientOnLine($users['client_id']) ? "在线" : "离线";
        $users['lineStateNum'] = $this->clientOnLine($users['client_id']) ? 1 : 0;

        return $users;
    }


    //判断一个客户端在线
    protected function clientOnLine($client_id)
    {
        $clientModel = new Client($this->modelDefaultParam());
        //在线状态，返回true，否则返回false
        return !empty($clientModel->getClientIdByUid($client_id));
    }

    //检测当前聊天对象
    protected function chkCurrentTarget($pid)
    {
        //聊天对象不得为空，并且聊天对象不能是自己
//        return !empty($pid) &&  $pid != session('user_id');
        return !empty($pid) &&  $pid != $this->getCurrentUserid(true);
    }


    //关闭同一个浏览器多个客服端页面
    protected function closeSameClient()
    {
        $clientModel = new Client($this->modelDefaultParam());
        //关闭同个浏览器另外一个聊天室链接
        $usermsg = $clientModel->getClientIdByUid($this->getCurrentUserid(true));
        if(!empty($usermsg))
        {
            $clientModel->closeClient($usermsg[0]);
        }
    }

    //绑定用户
    public function bind_user()
    {
        /**
         * 参数说明
         * post client_id 客户端id
         */
        $client_id  = input('post.client_id');

        $UserModel  = new Client($this->modelDefaultParam());
        //关闭之前的链接
        $client = $UserModel->getClientIdByUid();
        if(!empty($client) && isset($client[0]))
        {
            $UserModel->closeClient($client[0]);
        }

        $result     = $UserModel->bind_user($client_id);
        //通知所有人该用户上线
        $this->clientOn($result['client_id']);
        return $result;
    }

    //给用户发送消息
    public function send_text()
    {
        /**
         * 参数说明
         * post type text 为文本消息 photo 为图片消息
         * post type data 对应消息类型的内容
         * post to_client_id 对方的enc_client_id
         * post f_client_id  enc_client_id
         * post token
         * return {error,msg}
         */
        $post       = ArrRemoveJs(input('post.'));
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token'])  || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            return ['error'=>1,'error'=>'错误'];
        }

        $clientModel  = new Client($this->modelDefaultParam());
        $result     = $clientModel->send_text($post);

        //检查对方是否在线
        $userModel = new Users();
        $toUserInfo = $userModel->user_info(['enc_client_id'=>$post['to_client_id']]);
        if($toUserInfo['is_kf'] == 1 && !$this->clientOnLine($post['to_client_id']))
        {
            //给当前发送人发送离线推送
            $this->sendKfOffLineText($post['f_client_id']);
        }

        return $result;
    }

    public function send_photo()
    {
        $post = input('post.');
        //token验证
        if(!isset($post['image'])
            || !isset($post['f_client_id'])
            || !isset($post['token']) || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            return json_encode(['error'=>1,'error'=>'错误'],JSON_UNESCAPED_UNICODE);
        }

        $img = $post['image'];
        $path[0] = './uploads';
        $path[1] = "/chat_msg";
        $path[2] = $path[0].$path[1]."/".date('Ymd');
        $type_limit = array('jpg','jpeg','png');

        if(preg_match('/data:\s*image\/(\w+);base64,/iu',$img,$tmp)){
            if(!in_array($tmp[1],$type_limit)){
                $res["error"] = 2;
                $res["msg"] = "图片错误";
                return $res;
            }
        }else{
            $res["error"] = 3;
            $res["msg"] = "图片错误";
            return $res;
        }

        $img = str_replace(' ','+',$img);
        $img = str_replace($tmp[0], '', $img);
        $img = base64_decode($img);

        $file_name = md5($post['f_client_id'].time()).'.'.$tmp[1];
        $file = $path[2]."/".$file_name;
        if(!is_dir($path[0])) mkdir($path[0],0777);
        if(!is_dir($path[0].$path[1])) mkdir($path[0].$path[1],0777);
        if(!is_dir($path[2])) mkdir($path[2],0777);
        if(!file_put_contents($file,$img)){
            $res["error"] = 1;
            $res["msg"] = "图片错误";
            return $res;
        }else{
            $post['type'] = 'photo';
            $post['msg']  = $this->config('domain')."/"."public/".str_replace('./',"",$file);
            //客户端发送
            $userModel  = new Client($this->modelDefaultParam());
            $result     = $userModel->send_text($post);
            return json_encode($result,JSON_UNESCAPED_UNICODE);
        }

    }

    //获取最近的聊天记录
    public function getLateMsg()
    {
        /**
         * 参数说明
         * post to_client_id        当前对话的enc_client_id
         * post f_client_id  操作者enc_client_id
         * post token       token令牌
         * post msgid  最早对话的msgid，获取比这个消息id更小的id即更早的消息记录
         *
         */
        $post = input('post.');
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            return ['error'=>1,'token'=>'错误'];
        }
        $MsgModel = new ChatMsg($this->modelDefaultParam());
        $log = $MsgModel->getlog($this->getCurrentUserid(true),$post['to_client_id'],$post['msgid']);
        //客户端给当前用户发送历史消息
        $clientModel = new Client($this->modelDefaultParam());
        $clientModel->sendOneUser(['type'=>'history','msg'=>$log,'client_id'=>$post['f_client_id']],$this->getCurrentUserid(true));
    }


    //获取最近聊天的用户列表
    public function getLateUser()
    {
        /**
         * 参数说明
         * post.f_client_id  对方的client_id 即数据库中的enc_client_id
         * post.token       [如果client_id是客服账号，则无需该参数]当前用户请求的合法token
         */
        $input = input('post.');
        //验证参数以及该用户是否在线状态
        if(
            !isset($input['f_client_id'])
            || !isset($input['token'])
            || !$this->clientOnLine($input['f_client_id'])
        )
        {
            return ['error'=>'1','msg'=>"非法操作"];
        }

        $msgModel = new ChatMsg();
        $userModel = new Users();
        $clientModel= new Client();

        //获取用户
        if(!$info = $userModel->user_info(['enc_client_id'=>$input['f_client_id']])){ return ['error'=>1,'非法操作']; };
        //检查token，并加载数据
        if($this->chkToken(['token'=>$input['token'],'enc_client_id'=>$input['f_client_id']]))
        {
            //发联系列表通过soket发送
            $data = $msgModel->getLogUser($input['f_client_id']);
            $clientModel->sendOneUser(['type'=>'userList','msg'=>['data'=>$data,'is_kf'=>1]],$input['f_client_id']);
        }
        else
        {
            return ['error'=>1,'非法操作'];
        }

    }

    //自动回复请求
    public function autoReply()
    {

        /**
         * 参数说明
         * post type text 为文本消息 photo 为图片消息
         * post type data 对应消息类型的内容
         * post to_client_id 对方的enc_client_id
         * post f_client_id  enc_client_id
         * post token
         * return {error,msg}
         */
        $post       = input('post.');
        //token验证
        if(!isset($post['id'])
            ||!isset($post['f_client_id'])
            || !isset($post['token'])  || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            return ['error'=>1,'error'=>'错误'];
        }
        $ReplyModel = new KfReply();
        $data = $ReplyModel->info(['id'=>$post['id']]);
        $userModel = new Users();
        $ToClient = $userModel->user_info(['enc_client_id'=>$post['to_client_id']]);
        if(!empty($data))
        {
            //把对话方式对换
            $post['to_client_id'] = $post['f_client_id'];

            $data['content'] = urldecode($data['content']);
            $post['type'] = 'text';
            $post['msg'] = "
                问题：<span style='color:#0099ff'>{$data['title']} </span><br>
                {$data['content']}
            ";
            $userModel  = new Client(['user_id'=>$ToClient['client_id'],'user_name'=>$ToClient['nickname'],'nickname'=>$ToClient['nickname'],'isKf'=>$ToClient['is_kf']]);
            $result     = $userModel->send_text($post);
        }
        return $result;
    }
}